<!-- src/components/ValidCode.vue -->
<template>
  <div class="valid-code disabled-select" :style="{ width, height }" @click="generateCode">
    <span v-for="(item, index) in codeList" :key="index" :style="getStyle(item)">
      {{ item.code }}
    </span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

interface CodeChar {
  code: string;
  color: string;
  fontSize: string;
  padding: string;
  transform: string;
}

// 接收 props（带默认值）
const props = withDefaults(
  defineProps<{
    modelValue?: string;
    width?: string;
    height?: string;
    length?: number;
  }>(),
  {
    width: "100px",
    height: "32px",
    length: 4
  }
);

// v-model 支持
const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();

// 验证码数组
const codeList = ref<CodeChar[]>([]);

// 可选字符集
const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz23456789";

// 生成验证码
const generateCode = () => {
  const tempList: CodeChar[] = [];
  for (let i = 0; i < props.length; i++) {
    const rgb = [Math.floor(Math.random() * 180), Math.floor(Math.random() * 180), Math.floor(Math.random() * 180)];
    tempList.push({
      code: chars.charAt(Math.floor(Math.random() * chars.length)),
      color: `rgb(${rgb.join(",")})`,
      fontSize: `${14 + Math.floor(Math.random() * 8)}px`,
      padding: `${Math.floor(Math.random() * 4)}px`,
      transform: `rotate(${Math.floor(Math.random() * 60) - 30}deg)`
    });
  }

  codeList.value = tempList;
  emit("update:modelValue", tempList.map(item => item.code).join(""));
};

// 生成验证码样式
const getStyle = (item: CodeChar) => `
    color: ${item.color};
    font-size: ${item.fontSize};
    padding: ${item.padding};
    transform: ${item.transform};
  `;

onMounted(generateCode);
</script>

<style scoped>
.valid-code {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.disabled-select {
  user-select: none;
}
</style>
